package com.boil.qz.safekavass.websocket;

import com.boil.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * WebSocket 配置。
 *
 * @author ChenYong
 * @date 2016-10-31
 */
@Configuration
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
    /**
     * 日志
     */
    private static Logger log = LoggerFactory.getLogger(WebSocketConfig.class);
    /**
     * 注入 WebSocket 文本服务器
     */
    @Autowired
    private WebSocketTextServer webSocketTextServer;
    /**
     * 注入 WebSocket 拦截器
     */
    @Autowired
    private WebSocketInterceptor webSocketInterceptor;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 支持跨域访问：setAllowedOrigins("*")
        registry.addHandler(webSocketTextServer, "web/websocket/server").addInterceptors(webSocketInterceptor).setAllowedOrigins(Constants.ASTERISK_CHAR);
        registry.addHandler(webSocketTextServer, "web/websocket/sockjs/server").addInterceptors(webSocketInterceptor).setAllowedOrigins(Constants.ASTERISK_CHAR).withSockJS();

        log.info("WebSocket 文本服务器：{}--->启动成功", webSocketTextServer);
    }
}